package com.xiaoq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.RestException;

@ControllerAdvice
@ResponseBody
public class ExceptionAdvice extends ResponseEntityExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseEntity<?> handleException(Exception e) {
		logger.warn("未处理异常", e);
		GenericResponse resp = new GenericResponse(GenericResponse.CODE_NG, "未知错误");
		return new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
	}
	
	@ExceptionHandler(RestException.class)
    @ResponseBody
    public ResponseEntity<?> HandlerException(RestException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("Rest异常", ex);
		}
        int errCode = ex.getErrorCode();
        if (errCode == 0) {
            errCode = ex.getHttpStatus().value();
        }    
        GenericResponse resp = new GenericResponse(errCode + "", ex.getMessage());
        return new ResponseEntity<GenericResponse>(resp, ex.getHttpStatus());
    }

}